<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档管理</title>
    <style>
        .search-bar {
            margin-bottom: 20px;
        }

        .search-bar input {
            width: 80%;
            padding: 10px;
            font-size: 16px;
            margin-right: 10px;

        }

        .search-bar button {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table th,
        table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ddd;
        }

        table th {
            background-color: #f4f4f4;
        }

        /* 为选中的行添加样式 */
        tr.selected {
            background-color: #f0f0f0;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            min-height: 40vh;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
    <link rel="stylesheet" href="/styles.css">
</head>

<body>
<div class="container">
    <div class="search-bar">
        <input type="text" id="searchInput" placeholder="请输入关键词进行搜索">
        <button onclick="searchDocuments()">搜索</button>
    </div>
    <div class="doc-actions">
        <button id="deleteButton" onclick="deleteSelectedDocuments()">删除文章</button>
        <button onclick="window.location.href='/admin/home/addArticle'">添加文章</button>
        <button onclick="loginout()">退出登录</button>
    </div>
    <table>
        <thead>
        <tr>
            <th>选择</th>
            <th>序号</th>
            <th>标题</th>
            <th>内容</th>
            <th>分类</th>
            <th>来源</th>
            <th>活动日期</th>
            <th>浏览量</th>
            <th>评论</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="documentTableBody">
        <!-- 表格行将通过 JavaScript 动态插入 -->
        </tbody>
    </table>
    <div class="pagination">
        <button onclick="prevPage()">上一页</button>
        <span id="currentPage">1</span> / <span id="totalPages">1</span>
        <button onclick="nextPage()">下一页</button>
    </div>
</div>

<!-- 模态框 -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2 id="modalTitle"></h2>
        <p id="modalContent"></p>
    </div>
</div>

<script>
    let documents = [
        { id: 0, theme: '文档标题0', content: '文档内容0', type: '分类0', origin: '来源0zzzzzzzzzzz', date: '2024-05-29', clicks: 100 },
        { id: 1, theme: '文档标题1', content: '文档内容1zzzzzzzzz', type: '分类1', origin: '来源1', date: '2024-05-30', clicks: 150 },
        { id: 2, theme: '学校活动zzzzzzzzzz', content: '文档内容2', type: '分类2xxxxx', origin: '来源2', date: '2024-05-31', clicks: 200 },
        { id: 3, theme: '学校活动', content: '文档内容3XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', type: '分类3xxxxx', origin: '来源3', date: '2024-05-31', clicks: 200 },
        { id: 4, theme: '信息', content: '文档内容4', type: '分类4xxx', origin: '来源4', date: '2024-05-31', clicks: 200 }
    ];

    const tbody = document.getElementById('documentTableBody');
    const searchInput = document.getElementById('searchInput');
    const currentPageElement = document.getElementById('currentPage');
    const totalPagesElement = document.getElementById('totalPages');
    const modal = document.getElementById('myModal');
    const modalTitle = document.getElementById('modalTitle');
    const modalContent = document.getElementById('modalContent');
    const closeBtn = document.getElementsByClassName("close")[0];

    let currentPage = 1;
    let pageSize = 10; // 每页显示的文档数量
    let filteredDocs = documents;
    let totalPages = 0;

    const getdata = () => {
        const keyword = searchInput.value.toLowerCase();
        const url = `/article/search?keyword=${keyword}&pageNow=${currentPage}&pageSize=${pageSize}`;
        fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        })
            .then(response => response.json())
            .then(data => {
                console.log('data', data);
                if (data.code === 0) {
                    documents = data.data.articles;
                    console.log("documents", documents)
                    filteredDocs = documents;
                    totalPages = data.data.totalPages;
                    totalPagesElement.textContent = totalPages;
                    updatePagination()
                }
                else {
                    alert(data.message)
                }
            })
    }
    getdata()

    function renderDocuments(docs) {
        tbody.innerHTML = '';
        docs.forEach((doc) => {
            const tr = document.createElement('tr');
            tr.setAttribute('article-id', doc.id);

            tr.appendChild(createTd(`<input type="checkbox" class="doc-checkbox" data-doc-id="${doc.id}">`));
            tr.appendChild(createTd(doc.id.toString()));
            tr.appendChild(createTd(doc.theme));
            tr.appendChild(createTd('<button onclick="viewContent(' + doc.id + ')">查看</button>'));
            tr.appendChild(createTd(doc.type));
            tr.appendChild(createTd(doc.origin));
            tr.appendChild(createTd(doc.date));
            tr.appendChild(createTd(doc.clicks.toString()));
            tr.appendChild(createTd('<button onclick="viewComment(' + doc.id + ')">查看</button>'));
            tr.appendChild(createTd('<button onclick="editDocument(' + doc.id + ')">修改</button>'));
            tbody.appendChild(tr);
        });
    }

    function createTd(content) {
        const td = document.createElement('td');
        td.innerHTML = content;
        return td;
    }

    function searchDocuments() {
        getdata()
        currentPage = 1; // 重置到第一页
        // updatePagination();
    }

    searchInput.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            searchDocuments();
        }
    });

    function updatePagination() {
        const total = filteredDocs.length;
        // const totalPages = Math.ceil(total / pageSize);
        currentPageElement.textContent = currentPage;
        totalPagesElement.textContent = totalPages;

        // const start = (currentPage - 1) * pageSize;
        // const end = start + pageSize;
        renderDocuments(filteredDocs);
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            getdata()
            // updatePagination();
        }
    }

    function nextPage() {
        // const totalPages = Math.ceil(filteredDocs.length / pageSize);

        if (currentPage < totalPages) {
            currentPage++;
            getdata()
            // updatePagination();
        }
    }

    function generateVerificationCode() {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let code = '';
        for (let i = 0; i < 6; i++) {
            code += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        return code;
    }

    function deleteSelectedDocuments() {
        const checkboxes = document.querySelectorAll('.doc-checkbox');
        const selectedIds = [];

        checkboxes.forEach((checkbox) => {
            if (checkbox.checked) {
                const docId = parseInt(checkbox.dataset.docId);
                selectedIds.push(docId);
            }
        });

        if (selectedIds.length > 0) {
            const confirmDelete = confirm('确定要删除选中的文档吗？');
            if (confirmDelete) {
                const verificationCode = generateVerificationCode();
                const userInput = prompt(`请输入验证码 ${verificationCode} 以确认删除操作`);
                if (userInput === verificationCode) {
                    documents = documents.filter(doc => !selectedIds.includes(doc.id));
                    filteredDocs = documents;
                    currentPage = 1; // 重置到第一页
                    getdata()
                    // updatePagination();

                    selectedIds.forEach(async (id) => {
                        try {
                            const response = await fetch(`/article/${id}`, {
                                method: 'DELETE',
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            });
                            const data = await response.json();
                            if (data.code === 0) {
                                //弹出信息
                                alert('删除成功');
                                console.log(`文章 ${id} 删除成功`);
                                window.location.reload();
                            } else {
                                //弹出信息
                                alert('删除失败');
                                console.error(`文章 ${id} 删除失败: ${data.message}`);
                            }
                        } catch (error) {
                            alert('删除时发生错误');
                            console.error(`删除文章 ${id} 时发生错误:`, error);
                        }
                    });
                } else {
                    alert('验证码输入错误，删除操作取消');
                }
            }
        }
    }

    const viewComment = (id) => {
        console.log("id", id);
        console.log('查看评论');
        window.location.href = `/admin/home/comments?id=${id}`
    };

    const viewContent = (id) => {
        const doc = documents.find(doc => doc.id === id);
        if (doc) {
            modalTitle.textContent = doc.theme;
            modalContent.innerHTML = doc.content;
            modal.style.display = "block";
        }
    };

    const editDocument = (id) => {
        console.log("id", id);
        console.log('修改文章');
        window.location.href = `/admin/home/editArticle?id=${id}`;
    };

    // 处理复选框选中状态的视觉反馈
    tbody.addEventListener('change', function (event) {
        if (event.target.classList.contains('doc-checkbox')) {
            const tr = event.target.closest('tr');
            if (event.target.checked) {
                tr.classList.add('selected');
            } else {
                tr.classList.remove('selected');
            }
        }
    });

    // 关闭模态框
    closeBtn.onclick = function () {
        modal.style.display = "none";
    }

    // 点击模态框外部关闭模态框
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

    const loginout = () => {
        fetch('/admin/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                if (!response.ok) {
                    alert('登出失败');
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 0) {
                    console.log('登出成功');
                    window.location.href = '/admin/login'; // 跳转到管理员管理页面
                } else {
                    console.error('登出失败', data);
                }
            })
    }

    // // 初始化表格和分页
    // updatePagination();
</script>
</body>

</html>